<?php

namespace app\admin\controller;

use app\model\BizGoodsModel;
use app\model\BizModel;
use app\model\BizGoodsImageModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;
use app\model\PayPingModel;
use app\model\BizGoodsOrderModel;

class BizGoodsController
{
    public function index(Request $request): Response {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $title = $request->get('title', '');
            $bizId = $request->get('biz_id', '');
            
            $query = BizGoodsModel::query()
                ->whereNull('deleted_at')
                ->orderBy('id', 'desc');

            // 按商品名称搜索
            if (!empty($title)) {
                $query->where('title', 'like', '%' . $title . '%');
            }

            // 按商家ID搜索
            if (!empty($bizId)) {
                $query->where('biz_id', $bizId);
            }

            $status = $request->get('status', '');
            if (in_array($status, [0, 1])) {
                $query->where('status', $status);
            }

            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['image_url'] = Util::pathToUrl($item->image);
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);

                $biz = BizModel::find($item->biz_id);
                $item['biz_name'] = $biz ? $biz->name : '';

                $item['image_total'] = BizGoodsImageModel::where('goods_id', $item->id)->count();
                $item['sellout_count'] = BizGoodsOrderModel::where('biz_goods_id', $item->id)->where('status','=','pay')->count();

                $item['ping_count'] = PayPingModel::where('goods_id', $item->id)->where('type','=','biz-order')->count();
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    
    /**
     * 提交/创建商家
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['title']) || empty($data['image'])) {
                throw new Exception('商品名称和图片不能为空');
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $goods = BizGoodsModel::find($data['id']);
                if (!$goods) {
                    throw new Exception('商品不存在');
                }
            } else {
                $goods = new BizGoodsModel();
            }

            $goods->fill($data);
            $goods->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $goods->created_at = time();
            }
            
            if (!$goods->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $goods,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $goods = BizGoodsModel::find($id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $goods->deleted_at = time();
            if (!$goods->save()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品相册列表
     * @param Request $request
     * @return Response
     */
    public function getImages(Request $request): Response
    {
        try {
            $goodsId = $request->get('goods_id');
            if (empty($goodsId)) {
                throw new Exception('商品ID不能为空');
            }

            // 验证商品是否存在
            $goods = BizGoodsModel::find($goodsId);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $images = BizGoodsImageModel::where('goods_id', $goodsId)
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'desc')
                ->get();

            foreach ($images as &$image) {
                $image['url'] = Util::pathToUrl($image->path);
                $image['created_at'] = date('Y-m-d H:i:s', $image->created_at);
            }

            return json([
                'data' => $images,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 添加商品图片
     * @param Request $request
     * @return Response
     */
    public function addImage(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['goods_id']) || empty($data['path'])) {
                throw new Exception('商品ID和图片路径不能为空');
            }

            // 验证商品是否存在
            $goods = BizGoodsModel::find($data['goods_id']);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $image = new BizGoodsImageModel();
            $image->goods_id = $data['goods_id'];
            $image->path = $data['path'];
            $image->title = $data['title'] ?? '';
            $image->sort = $data['sort'] ?? 0;
            $image->created_at = time();
            $image->updated_at = time();

            if (!$image->save()) {
                throw new Exception('添加图片失败');
            }

            $image['url'] = Util::pathToUrl($image->path);

            return json([
                'data' => $image,
                'msg' => '添加成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除商品图片
     * @param Request $request
     * @return Response
     */
    public function deleteImage(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('图片ID不能为空');
            }

            $image = BizGoodsImageModel::find($id);
            if (!$image) {
                throw new Exception('图片不存在');
            }

            // 删除物理文件
            if (!empty($image->path) && file_exists($image->path)) {
                Util::deleteFile($image->path);
            }

            if (!$image->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新图片排序
     * @param Request $request
     * @return Response
     */
    public function updateImageSort(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['images']) || !is_array($data['images'])) {
                throw new Exception('排序数据格式错误');
            }

            foreach ($data['images'] as $item) {
                if (empty($item['id']) || !isset($item['sort'])) {
                    continue;
                }

                $image = BizGoodsImageModel::find($item['id']);
                if ($image) {
                    $image->sort = $item['sort'];
                    $image->updated_at = time();
                    $image->save();
                }
            }

            return json([
                'data' => null,
                'msg' => '排序更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新图片信息
     * @param Request $request
     * @return Response
     */
    public function updateImage(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['id'])) {
                throw new Exception('图片ID不能为空');
            }

            $image = BizGoodsImageModel::find($data['id']);
            if (!$image) {
                throw new Exception('图片不存在');
            }

            if (isset($data['title'])) {
                $image->title = $data['title'];
            }
            if (isset($data['sort'])) {
                $image->sort = $data['sort'];
            }
            $image->updated_at = time();

            if (!$image->save()) {
                throw new Exception('更新失败');
            }

            $image['url'] = Util::pathToUrl($image->path);

            return json([
                'data' => $image,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 切换商品上下架状态
     * @param Request $request
     * @return Response
     */
    public function toggleStatus(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('商品ID不能为空');
            }

            $goods = BizGoodsModel::find($id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            // 切换状态：1变0，0变1
            $newStatus = $goods->status === 1 ? 0 : 1;
            $goods->status = $newStatus;
            $goods->updated_at = time();
            $goods->save();

            $statusText = $newStatus === 1 ? '上架' : '下架';

            return json([
                'data' => [
                    'id' => $goods->id,
                    'status' => $newStatus,
                    'status_text' => $statusText
                ],
                'msg' => '商品已' . $statusText,
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
